package com.home.administrator.okhttplibrary;

import android.content.Context;
import android.os.AsyncTask;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import okhttp3.Cache;
import okhttp3.Cookie;
import okhttp3.CookieJar;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2016-5-31.
 */
public abstract class OkHttpTask {
	private static OkHttpClient okHttpClient;
	private static OkHttpTaskBuidler okHttpTask;
	private static CookieJar cookieJar = new CookieJar() {
		private final HashMap<String, List<Cookie>> cookieStore = new HashMap<String, List<Cookie>>();

		@Override
		public void saveFromResponse(HttpUrl url, List<Cookie> cookies) {
			cookieStore.put(url.host(), cookies);
		}

		@Override
		public List<Cookie> loadForRequest(HttpUrl url) {
			List<Cookie> cookies = cookieStore.get(url.host());
			return cookies != null ? cookies : new ArrayList<Cookie>();
		}
	};

	// public static final String URL_REGEX =
	// "((http|ftp|https)://)(([a-zA-Z0-9\\._-]+\\.[a-zA-Z]{2,6})|([0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}))(:[0-9]{1,4})*(/[a-zA-Z0-9\\&%_\\./-~-]*)?";

	public static OkHttpClient newinstance(Context context) {
		if (okHttpClient == null) {
			synchronized (OkHttpTask.class) {
				File cacheDir = context.getCacheDir();
				okHttpClient = new OkHttpClient.Builder()
						.addInterceptor(new CacheInterceptor(context))
						.cookieJar(cookieJar)
						.cache(new Cache(cacheDir, 100 * 1024 * 1024)).build();
			}
		}
		return okHttpClient;
	}

	/**
	 * 单例模式
	 * 
	 * @param context
	 * @return
	 */
	public static OkHttpTaskBuidler newInstance(Context context) {
		if (okHttpClient == null) {
			synchronized (OkHttpTask.class) {
				File cacheDir = context.getCacheDir();
				okHttpClient = new OkHttpClient.Builder()
						.addInterceptor(new CacheInterceptor(context))
						.cookieJar(cookieJar)
						.cache(new Cache(cacheDir, 100 * 1024 * 1024)).build();
			}
		}
		okHttpTask = new OkHttpTaskBuidler();
		return okHttpTask;
	}

	/**
	 * 工程模式
	 * 
	 * @author Administrator
	 */
	public static class OkHttpTaskBuidler extends
			AsyncTask<String, Integer, String> {

		private IOkTaskCallback iOkTaskCallback;
		private boolean post;
		private String headerName;
		private String headerValue;
		private RequestBody formBody;

		public enum OkType {
			form, json
		}

		public void start(String url) {
			if (url == null) {
				throw new NullPointerException("url is null");
			}
			// if (!url.matches(URL_REGEX)) {
			// throw new IllegalArgumentException("URL is wrong");
			// }
			this.execute(url);
		}

		public OkHttpTaskBuidler enqueue(IOkTaskCallback iOkTaskCallback) {
			this.iOkTaskCallback = iOkTaskCallback;
			return OkHttpTaskBuidler.this;
		}

		/**
		 * post请求传头部
		 * 
		 * @Description: TODO
		 * @param @param name
		 * @param @param value
		 * @return void
		 * @throws
		 * @author fzq
		 * @date 2017-10-27
		 */
		public OkHttpTaskBuidler addHeader(String name, String value) {
			headerName = name;
			headerValue = value;
			return OkHttpTaskBuidler.this;
		}

		/**
		 * post请求上传body
		 * 
		 * @Description: TODO
		 * @param @param param
		 * @param @param type
		 * @param @return
		 * @return OkHttpTaskBuidler
		 * @throws
		 * @author fzq
		 * @date 2017-10-27
		 */
		public OkHttpTaskBuidler post(Map<String, String> param, OkType type) {
			if (param == null) {
				throw new NullPointerException("param is null");
			}
			post = true;
			switch (type) {
			case form:
				FormBody.Builder builder = new FormBody.Builder();
				Set<String> strings = param.keySet();
				for (String str : strings) {
					builder.add(str, param.get(str));
				}
				formBody = builder.build();
				break;
			case json:
				try {
					MediaType mediaType = MediaType
							.parse("application/json; charset=utf-8");
					JSONObject jsonObject = new JSONObject();
					Set<String> keySet = param.keySet();
					for (String key : keySet) {
						jsonObject.put(key, param.get(key));
					}
					RequestBody.create(mediaType, jsonObject.toString());
				} catch (JSONException e) {
					e.printStackTrace();
				}
				break;

			}
			return OkHttpTaskBuidler.this;
		}

		@Override
		protected String doInBackground(String... params) {
			String url = params[0];
			Request.Builder builder = new Request.Builder();
			if (headerName != null && headerValue != null) {
				builder.addHeader(headerName, headerValue);
			}
			Response response = null;
			try {
				if (post) {
					builder.post(formBody);
				}
				Request request = builder.url(url).build();
				response = okHttpClient.newCall(request).execute();
				String string = "";
				if (response.isSuccessful()){
				    string = response.body().string();
				}
				return string;
			} catch (IOException e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(String s) {
			super.onPostExecute(s);
			if (iOkTaskCallback != null ) {
				iOkTaskCallback.onSuccess(s);
			}
		}
	}
}
